from rest_framework import viewsets, status
from oAuth.models import Informations
from rest_framework import serializers
from oAuth.serializers import Informationerializer
from rest_framework.response import Response
from rest_framework import filters
from django.db.models import Q

#得到关于机器故障次数的饼图
class MachinePieViewSet(viewsets.ModelViewSet):
    queryset = Informations.objects.all().filter(Q(is_delete=False))
    serializer_class = Informationerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        all_data = {
            'name': [],
            'data': []
        }
        k = {}
        for i in range(len(serializer.data)):
            t = serializer.data[i]

            if t['is_delete'] == True:
                continue
            if str(t['number']) not in all_data['name']:
                all_data['name'].append(str(t['number']))
            if str(t['number']) not in k:
                k[str(t['number'])] = 1
            else:
                k[str(t['number'])] += 1
        for i in k:
            all_data['data'].append({ 'value':k[i], 'name':str(i)})

        return Response(all_data)
#得到关于故障类型的饼图
class InformationPieViewSet(viewsets.ModelViewSet):
    queryset = Informations.objects.all().filter(Q(is_delete=False))
    serializer_class = Informationerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        all_data = {
            'name': [],
            'data': []
        }
        k = {}
        for i in range(len(serializer.data)):
            t = serializer.data[i]
            if t['is_delete'] == True:
                continue
            if str(t['shortage']) not in all_data['name']:
                all_data['name'].append(str(t['shortage']))
            if str(t['shortage']) not in k:
                k[str(t['shortage'])] = 1
            else:
                k[str(t['shortage'])] += 1
        for i in k:
            all_data['data'].append({ 'value':k[i], 'name':str(i)})

        return Response(all_data)


#得到关于时间故障次数的饼图
class ShortagePieViewSet(viewsets.ModelViewSet):
    queryset = Informations.objects.all().filter(Q(is_delete=False))
    serializer_class = Informationerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        all_data = {
            'name': [],
            'data': []
        }
        k = {}
        for i in range(len(serializer.data)):
            t = serializer.data[i]
            if t['is_delete'] == True:
                continue
            if str(t['shortage']) not in all_data['name']:
                all_data['name'].append(str(t['shortage']))
            if str(t['shortage']) not in k:
                k[str(t['shortage'])] = 1
            else:
                k[str(t['shortage'])] += 1
        for i in k:
            all_data['data'].append({ 'value':k[i], 'name':str(i)})
        return Response(all_data)

class TimePieViewSet(viewsets.ModelViewSet):
    queryset = Informations.objects.all().filter(Q(is_delete=False))
    serializer_class = Informationerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        all_data = {
            'name': [],
            'data': []
        }
        k = {}
        for i in range(len(serializer.data)):
            t = serializer.data[i]
            time = t['occure_time'][:7]
            if t['is_delete'] == True:
                continue
            if str(time) not in all_data['name']:
                all_data['name'].append(str(time))
            if str(time) not in k:
                k[str(time)] = 1
            else:
                k[str(time)] += 1
        for i in k:
            all_data['data'].append({ 'value':k[i], 'name':str(i)})
        return Response(all_data)


# 详细细节图
class MachineDetailViewSet(viewsets.ModelViewSet):
    queryset = Informations.objects.all().filter(Q(is_delete=False))
    serializer_class = Informationerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        all_data = {
            'name': [],
            'data': [],
            'time': [],
        }
        k = {}
        for i in range(len(serializer.data)):
            t = serializer.data[i]
            time = t['occure_time'][:7]
            if t['is_delete'] == True:
                continue
            #获得x轴坐标
            if str(time) not in all_data['time']:
                all_data['time'].append(str(time))
            #获得那些作为要展示的值
            if str(t['number']) not in all_data['name']:
                all_data['name'].append(str(t['number']))

            #弄出来每一个属性的serires
            if str(t['number']) not in k:
                k[str(t['number'])] = {}

            if time not in k[str(t['number'])]:
                k[str(t['number'])][time] = 1
            else:
                k[str(t['number'])][time] += 1


        all_data['time'].sort()


        for i in k:
            tmp = k[i]
            tmp  = sorted(tmp)
            cnt = []
            for j in tmp:
                cnt.append(k[i][j])
            all_data['data'].append({
                'name':i,
                'type':'line',
                'stack':'Total',
                'data': cnt
            })

        len_max = 0
        for i in all_data['data']:
            len_max = max(len_max, len(i['data']))

        for i in all_data['data']:
            while len(i['data']) < len_max:
                i['data'].append(0)
        return Response(all_data)

class ShortageDetailViewSet(viewsets.ModelViewSet):
    queryset = Informations.objects.all().filter(Q(is_delete=False))
    serializer_class = Informationerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        all_data = {
            'name': [],
            'data': [],
            'time': [],
        }
        k = {}
        for i in range(len(serializer.data)):
            t = serializer.data[i]
            time = t['occure_time'][:7]
            if t['is_delete'] == True:
                continue
            #获得x轴坐标
            if str(time) not in all_data['time']:
                all_data['time'].append(str(time))
            #获得那些作为要展示的值
            if str(t['shortage']) not in all_data['name']:
                all_data['name'].append(str(t['shortage']))

            #弄出来每一个属性的serires
            if str(t['shortage']) not in k:
                k[str(t['shortage'])] = {}

            if time not in k[str(t['shortage'])]:
                k[str(t['shortage'])][time] = 1
            else:
                k[str(t['shortage'])][time] += 1


        all_data['time'].sort()

        for i in k:
            tmp = k[i]
            tmp  = sorted(tmp)
            cnt = []
            for j in tmp:
                cnt.append(k[i][j])
            all_data['data'].append({
                'name':i,
                'type':'line',
                'stack':'Total',
                'data': cnt
            })

        len_max = 0
        for i in all_data['data']:
            len_max = max(len_max, len(i['data']))

        for i in all_data['data']:
            while len(i['data']) < len_max:
                i['data'].append(0)
        return Response(all_data)

class EveryShortageDetailViewSet(viewsets.ModelViewSet):
    queryset = Informations.objects.all().filter(Q(is_delete=False))
    serializer_class = Informationerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        all_data = {
            'name': [],
            'data': [],
            'time': [],
        }
        k = {}
        for i in range(len(serializer.data)):
            t = serializer.data[i]
            time = t['occure_time'][:7]
            if t['is_delete'] == True:
                continue
            # 获得x轴坐标
            if str(time) not in all_data['time']:
                all_data['time'].append(str(time))
            # 获得那些作为要展示的值
            if str(t['shortage']) not in all_data['name']:
                all_data['name'].append(str(t['shortage']))

            # 弄出来每一个属性的serires
            if str(t['shortage']) not in k:
                k[str(t['shortage'])] = {}

            if time not in k[str(t['shortage'])]:
                k[str(t['shortage'])][time] = 1
            else:
                k[str(t['shortage'])][time] += 1

        all_data['time'].sort()

        for i in k:
            tmp = k[i]
            tmp = sorted(tmp)
            cnt = []
            for j in tmp:
                cnt.append(k[i][j])
            all_data['data'].append({
                'name': i,
                'type': 'line',
                'stack': 'Total',
                'data': cnt
            })

        t = {}
        res_data = {
            'name': all_data['name'],
            'time': all_data['time'],
            'data': [],
        }
        j = 0
        for i in all_data['name']:
            t[i] = {
                'name': i,
                'type': 'bar',
                'data': all_data['data'][j]['data']
            }
            tmp = [t[i]]
            t[i] = {
                'name': i,
                'type': 'line',
                'data': all_data['data'][j]['data']
            }
            tmp.append(t[i])
            res_data['data'].append(tmp)
            j += 1


        return Response(res_data)


class EveryMachineDetailViewSet(viewsets.ModelViewSet):
    queryset = Informations.objects.all().filter(Q(is_delete=False))
    serializer_class = Informationerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        all_data = {
            'name': [],
            'data': [],
            'time': [],
        }
        k = {}
        for i in range(len(serializer.data)):
            t = serializer.data[i]
            time = t['occure_time'][:7]

            if t['is_delete'] == True:
                continue

            # 获得x轴坐标
            if str(time) not in all_data['time']:
                all_data['time'].append(str(time))
            # 获得那些作为要展示的值
            if str(t['number']) not in all_data['name']:
                all_data['name'].append(str(t['number']))

            # 弄出来每一个属性的serires
            if str(t['number']) not in k:
                k[str(t['number'])] = {}

            if time not in k[str(t['number'])]:
                k[str(t['number'])][time] = 1
            else:
                k[str(t['number'])][time] += 1

        all_data['time'].sort()
        tmpk = len(all_data['time'])
        all_data['time'] = all_data['time'][tmpk - 6:]

        for i in k:

            tmp = k[i]
            tmp = sorted(tmp)
            cnt = []
            for j in tmp:
                cnt.append(k[i][j])
            all_data['data'].append({
                'name': i,
                'type': 'line',
                'stack': 'Total',
                'data': cnt
            })

        t = {}
        res_data = {
            'name':all_data['name'],
            'time':all_data['time'],
            'data':[],
        }
        len_max = 0
        for i in all_data['data']:
            len_max = max(len_max, len(i['data']))

        for i in all_data['data']:
            while len(i['data']) < len_max:
                i['data'].append(0)

        for i in all_data['data']:
            k = len(i['data']) - 6
            for j in range(k):
                i['data'].pop(0)

        j = 0
        for i in all_data['name']:
            t[i] = {
                'name':i,
                'type':'bar',
                'data':all_data['data'][j]['data']
            }
            tmp = [t[i]]
            t[i] = {
                'name': i,
                'type': 'line',
                'data': all_data['data'][j]['data']
            }
            tmp.append(t[i])
            res_data['data'].append(tmp)
            j += 1


        return Response(res_data)

class MachineTimeViewSet(viewsets.ModelViewSet):
    queryset = Informations.objects.all().filter(Q(is_delete=False))
    serializer_class = Informationerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        all_data = {
            'name': [],
            'data': [],
            'time': [],
        }
        k = {}
        for i in range(len(serializer.data)):
            t = serializer.data[i]
            time = t['occure_time'][:7]
            if t['is_delete'] == True:
                continue
            #获得x轴坐标
            if str(time) not in all_data['time']:
                all_data['time'].append(str(time))
            #获得那些作为要展示的值
            if str(t['number']) not in all_data['name']:
                all_data['name'].append(str(t['number']))

            #弄出来每一个属性的serires
            if str(t['number']) not in k:
                k[str(t['number'])] = {}

            if time not in k[str(t['number'])]:
                k[str(t['number'])][time] = 1
            else:
                k[str(t['number'])][time] += 1


        all_data['time'].sort()


        for i in k:
            tmp = k[i]
            tmp  = sorted(tmp)
            cnt = []
            for j in tmp:
                cnt.append(k[i][j])
            all_data['data'].append({
                'name':i,
                'type':'line',
                'stack':'Total',
                'data': cnt
            })

        ans_data = {
            'yAxis':all_data['name'],
            'legend':['本月故障次数', '上月故障次数', '月故障增长数'],
            'data':[],
            'table':[]
        }
        this_month = []
        last_month = []
        dif_month = []

        for i in all_data['data']:
            this_month.append(i['data'][-1])
            last_month.append(i['data'][-2])
            dif_month.append(this_month[-1] - last_month[-1])

        ans_data['data'].append(this_month)
        ans_data['data'].append(last_month)
        ans_data['data'].append(dif_month)


        for i in range(len(ans_data['yAxis'])):
            ans_data['table'].append({
                'num':i,
                'machine':ans_data['yAxis'][i],
                'total':sum(all_data['data'][i]['data'])
            })

        return Response(ans_data)


class ShortageTimeViewSet(viewsets.ModelViewSet):
    queryset = Informations.objects.all().filter(Q(is_delete=False))
    serializer_class = Informationerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        all_data = {
            'name': [],
            'data': [],
            'time': [],
        }
        k = {}
        for i in range(len(serializer.data)):
            t = serializer.data[i]
            time = t['occure_time'][:7]

            if t['is_delete'] == True:
                continue
            #获得x轴坐标
            if str(time) not in all_data['time']:
                all_data['time'].append(str(time))
            #获得那些作为要展示的值
            if str(t['shortage']) not in all_data['name']:
                all_data['name'].append(str(t['shortage']))

            #弄出来每一个属性的serires
            if str(t['shortage']) not in k:
                k[str(t['shortage'])] = {}

            if time not in k[str(t['shortage'])]:
                k[str(t['shortage'])][time] = 1
            else:
                k[str(t['shortage'])][time] += 1


        all_data['time'].sort()


        for i in k:
            tmp = k[i]
            tmp  = sorted(tmp)
            cnt = []
            for j in tmp:
                cnt.append(k[i][j])
            all_data['data'].append({
                'name':i,
                'type':'line',
                'stack':'Total',
                'data': cnt
            })

        ans_data = {
            'yAxis':all_data['name'],
            'legend':['本月发生次数', '上月发生次数', '月故障增长数'],
            'data':[],
            'table':[]
        }
        this_month = []
        last_month = []
        dif_month = []

        for i in all_data['data']:
            this_month.append(i['data'][-1])
            last_month.append(i['data'][-2])
            dif_month.append(this_month[-1] - last_month[-1])

        ans_data['data'].append(this_month)
        ans_data['data'].append(last_month)
        ans_data['data'].append(dif_month)


        for i in range(len(ans_data['yAxis'])):
            ans_data['table'].append({
                'num':i,
                'machine':ans_data['yAxis'][i],
                'total':sum(all_data['data'][i]['data'])
            })

        return Response(ans_data)


# 这里开始写所有的按月分析
class Month_MachineViewSet(viewsets.ModelViewSet):
    queryset = Informations.objects.all().filter(Q(is_delete=False))
    serializer_class = Informationerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        month = []
        count = {}
        data = {
            'month':[],
        }
        for i in serializer.data:
            count[i['occure_time'][:7]] = count.get(i['occure_time'][:7], 0) + 1
            if i['occure_time'][:7] not in month and i['is_delete'] == False:
                month.append(i['occure_time'][:7])


        month.sort(reverse = True)
        for i in month:
            data['month'].append({'month':i, 'count':count[i], 'label': i})
        data['month'].insert(0, {'month':'首页', 'count': sum(count.values()),  'label': 'null    '})
        return Response(data)

    def create(self, request, *args, **kwargs):

        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        data = request.data
        month = data['month_value']
        cnt_now = {}
        cnt_last = {}
        cnt_year = {}
        cnt_last_year = {}
        all_data = {
            'pie_option':[],
            'time_option':{
                'number':[],
                'data_one':[],
                'data_two':[],
                'data_three':[]
            },
            'year_bar_option':{
                'number':[],
                'data': [],
            },
            'time_option_diff': {
                'data_one': [],
                'data_two': [],
            },
        }

        last_month = int(month[-2:]) - 1
        if last_month == 0:
            last_month = str(int(month[:4]) - 1) + '-' + '12'
        else:
            last_month = month[:5] + "{:02d}".format(int(month[-2:]) - 1)


        for i in serializer.data:
            time = i['occure_time']
            if i['is_delete'] == True:
                continue

            cnt_now[i['number']] = cnt_now.get(i['number'], 0)
            cnt_last[i['number']] = cnt_last.get(i['number'], 0)
            cnt_year[i['number']] = cnt_year.get(i['number'], 0)
            cnt_last_year[i['number']] = cnt_last_year.get(i['number'], 0)

            if i['number'] not in all_data['time_option']['number']:
                all_data['time_option']['number'].append(i['number'])
                all_data['year_bar_option']['number'].append(i['number'])

            if time[:7] == month:
                cnt_now[i['number']] = cnt_now.get(i['number']) + 1

            if time[:7] == last_month:
                cnt_last[i['number']] = cnt_last.get(i['number']) + 1

            if time[:4] == month[:4] and int(time[5:7]) <= int(month[-2:]):
                cnt_year[i['number']] = cnt_year.get(i['number']) + 1

            if int(time[:4]) == int(month[:4]) - 1 and int(time[5:7]) == int(month[-2:]):
                cnt_last_year[i['number']] = cnt_last_year.get(i['number']) + 1

        num_list = sorted(cnt_now)

        for i in num_list:
            all_data['pie_option'].append({'value':cnt_now[i], 'name':i})
            all_data['time_option']['data_one'].append(cnt_now[i])
            all_data['time_option']['data_two'].append(cnt_last[i])
            all_data['time_option']['data_three'].append(cnt_now[i] - cnt_last[i])
            all_data['year_bar_option']['data'].append(cnt_year[i])
            all_data['time_option_diff']['data_one'].append(cnt_last_year[i])
            all_data['time_option_diff']['data_two'].append(cnt_now[i] - cnt_last_year[i])

        all_data['time_option']['number'].sort()
        all_data['year_bar_option']['number'].sort()

        return Response(all_data)




class Month_ShortageViewSet(viewsets.ModelViewSet):
    queryset = Informations.objects.all().filter(Q(is_delete=False))
    serializer_class = Informationerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        month = []
        count = {}
        data = {
            'month': [],
            'cnt': []
        }
        for i in serializer.data:
            count[i['occure_time'][:7]] = count.get(i['occure_time'][:7], 0) + 1
            if i['occure_time'][:7] not in month and i['is_delete'] == False:
                month.append(i['occure_time'][:7])

        month.sort(reverse=True)
        for i in month:
            data['month'].append({'month': i, 'count': count[i]})
        data['month'].insert(0, {'month': '首页', 'count': sum(data['cnt'])})
        return Response(data)

    def create(self, request, *args, **kwargs):

        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        data = request.data
        month = data['month_value']
        cnt_now = {}
        cnt_last = {}
        cnt_year = {}
        cnt_last_year = {}
        all_data = {
            'pie_option':[],
            'time_option':{
                'shortage':[],
                'data_one':[],
                'data_two':[],
                'data_three':[]
            },
            'year_bar_option':{
                'shortage':[],
                'data': [],
            },
            'time_option_diff': {
                'data_one': [],
                'data_two': [],
            },
        }

        last_month = int(month[-2:]) - 1
        if last_month == 0:
            last_month = str(int(month[:4]) - 1) + '-' + '12'
        else:
            last_month = month[:5] + "{:02d}".format(int(month[-2:]) - 1)


        for i in serializer.data:
            time = i['occure_time']
            if i['is_delete'] == True:
                continue

            cnt_now[i['shortage']] = cnt_now.get(i['shortage'], 0)
            cnt_last[i['shortage']] = cnt_last.get(i['shortage'], 0)
            cnt_year[i['shortage']] = cnt_year.get(i['shortage'], 0)
            cnt_last_year[i['shortage']] = cnt_last_year.get(i['shortage'], 0)

            if i['shortage'] not in all_data['time_option']['shortage']:
                all_data['time_option']['shortage'].append(i['shortage'])
                all_data['year_bar_option']['shortage'].append(i['shortage'])

            if time[:7] == month:
                cnt_now[i['shortage']] = cnt_now.get(i['shortage']) + 1

            if time[:7] == last_month:
                cnt_last[i['shortage']] = cnt_last.get(i['shortage']) + 1

            if time[:4] == month[:4] and int(time[5:7]) <= int(month[-2:]):
                cnt_year[i['shortage']] = cnt_year.get(i['shortage']) + 1

            if int(time[:4]) == int(month[:4]) - 1 and int(time[5:7]) == int(month[-2:]):
                cnt_last_year[i['shortage']] = cnt_last_year.get(i['shortage']) + 1

        num_list = sorted(cnt_now)

        for i in num_list:
            all_data['pie_option'].append({'value':cnt_now[i], 'name':i})
            all_data['time_option']['data_one'].append(cnt_now[i])
            all_data['time_option']['data_two'].append(cnt_last[i])
            all_data['time_option']['data_three'].append(cnt_now[i] - cnt_last[i])
            all_data['year_bar_option']['data'].append(cnt_year[i])
            all_data['time_option_diff']['data_one'].append(cnt_last_year[i])
            all_data['time_option_diff']['data_two'].append(cnt_now[i] - cnt_last_year[i])

        all_data['time_option']['shortage'].sort()
        all_data['year_bar_option']['shortage'].sort()

        return Response(all_data)